<?php
require('country_list.php');
require('xml2array.php');

header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' . PHP_EOL;
echo '<Graph>' . PHP_EOL;

$firstCountry = addslashes(strip_tags($_REQUEST['country']));

if ( !empty($firstCountry) ) {
	echo "<Node id=\"$firstCountry\" prop=\"$firstCountry\" />" . PHP_EOL; // Every country is a node.
	// Any edges leaving from this node?
	if ( file_exists("matches/$firstCountry.xml") ) {
		printEdges($firstCountry);
	}
}

foreach($country_list as $country){

	if ( empty($firstCountry) || $country != $firstCountry ) {

		echo "<Node id=\"$country\" prop=\"$country\" />" . PHP_EOL; // Every country is a node.
		
		// Any edges leaving from this node?
		if ( file_exists("matches/$country.xml") ) {
			printEdges($country);
		}
		
	}
			
}

echo '</Graph>' . PHP_EOL;

function printEdges($country)
{
	$matches = xml2array("matches/$country.xml");
	$nbEdges = 0;
	for($c=0; $c<sizeof($matches['GeoMatches']['GeoMatch']); $c++) {
		if($matches['GeoMatches']['GeoMatch'][$c]['Similarity'] > 60 && $matches['GeoMatches']['GeoMatch'][$c]['Country'] != $country ) { // found one
			echo "<Edge fromID=\"$country\" toID=\"" . $matches['GeoMatches']['GeoMatch'][$c]['Country'] . "\" ";
			echo "similarity=\"" . $matches['GeoMatches']['GeoMatch'][$c]['Similarity'] . "\" />" . PHP_EOL;
			if (++$nbEdges == 4)
				$c = sizeof($matches['GeoMatches']['GeoMatch']); // 4 is enough
		}
	}
}

function countEdges($country)
{
}
?>